﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;

using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading;

namespace INSA
{
    public partial class FormMain : Form
    {
        DataTable tbl;

        const int widthPSeparator = 5;
        const int widthPExtended = 613;

        private static ToolStripMenuItem mnuStaticOpen;
        private static ToolStripMenuItem mnuStaticConfig;
        private static ToolStripMenuItem mnuStaticSubmit;
        private static ToolStripMenuItem mnuStaticMTagetsReg;
        private static Button btnStaticOpen;
        private static Button btnStaticClose;
        private static Button btnStaticUp;
        private static Button btnStaticDown;
        private static Button btnStaticAllot;
        private static Button btnStaticSave;
        private static Button btnStaticApply;

        private int checkCount = 0;
        private decimal originItemValue;

        public FormMain()
        {
            InitializeComponent();

            tbl = new DataTable();

            //환경변수 설정
            Config.Path = Application.StartupPath;  //응용프로그램 실행 경로
            Config.Version = "1.0";                 //버전
            Config.Mf = this;
            Config.EnabledListViewEvent = false;
            

            //MDB 연결
            DBUtil.oleConnect();

            Control.CheckForIllegalCrossThreadCalls = false;

            //전역 컨트롤 설정
            setStaticControls();            

            //사용자 등록 상태 확인
            if (DBUtil.isRegistedUserInfo())
            {
                Config.State = Config.STATE_OK;     //프로그램 사용 상태: 사용자 등록한 상태
            }
            else
            {
                Config.State = Config.STATE_INIT;   //프로그램 처음 실행
                setDisabled();                      //컨트롤 비활성화
            }

            //프로그램 사용 상태에 따라 컨트롤 활성 및 비활성
            if (Config.State == Config.STATE_OK)
            {                
                Config.setMvi();                    //사용자정보 설정
                setEnabled();                       //컨트롤 활성화
            }
            
        }

       
        

        /*********************************
         * 이벤트 모음
         ********************************/

        private void mnuValuerInfo_Click(object sender, EventArgs e)
        {
            Form f = new FormBasicInfo();
            f.ShowDialog(this);
           
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
            Util.closeXls();
        }

        private void mnuProgramInfo_Click(object sender, EventArgs e)
        {
            Form f = new FormProgramInfo();
            f.ShowDialog(this);
        }


        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //메인 폼이 닫혀졌을 때 MDB 연결 종료            
            DBUtil.oleClose();
            Util.closeXls();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                Config.EnabledListViewEvent = false;

                //확장 패널 보이게 하기
                this.SetBounds(this.Location.X, this.Location.Y, pMain.Size.Width + widthPSeparator + widthPExtended + 6, this.Height);

                //데이터그리드 비우기
                clearGrid();

                //그리드 초기화
                initMultiGrid((byte)cboTargetType.SelectedIndex);

                
                //대상자등록 메뉴와 평가자 정보 메뉴 Disabled
                mnuMTargetsReg.Enabled = false;
                mnuValuerInfo.Enabled = false;
                if (cboTargetType.SelectedIndex == 0)
                {
                    btnUp.Enabled = true;
                    btnDown.Enabled = true;
                    btnAllot.Enabled = true;
                }
                btnSave.Enabled = true;
                btnApply.Enabled = true;
                btnOpen.Enabled = false;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");

            }
        }

        private void setMultiInfoToGrid(int i, string pcode)
        {
            ArrayList list = DBUtil.getMTargetDetailInfo(pcode);
            if (list != null && list.Count > 0)
            {
                dgvMultiTable.Rows[i].Cells[4].Value = list[0];
                dgvMultiTable.Rows[i].Cells[5].Value = list[1];
                dgvMultiTable.Rows[i].Cells[6].Value = list[2];
                dgvMultiTable.Rows[i].Cells[7].Value = list[3];
                dgvMultiTable.Rows[i].Cells[8].Value = list[4];
                dgvMultiTable.Rows[i].Cells[9].Value = list[5];
            }
            else
            {
                dgvMultiTable.Rows[i].Cells[4].Value = 0.0;
                dgvMultiTable.Rows[i].Cells[5].Value = 0.0;
                dgvMultiTable.Rows[i].Cells[6].Value = 0.0;
                dgvMultiTable.Rows[i].Cells[7].Value = 0.0;
                dgvMultiTable.Rows[i].Cells[8].Value = 0.0;
                dgvMultiTable.Rows[i].Cells[9].Value = 0.0;
            }

        }

        /// <summary>
        /// 그리드에 다면평가 대상자 Row생성 및 그리드 칼럼 속성 설정
        /// </summary>
        /// <param name="targetType">대상자유형</param>
        private void initMultiGrid(byte targetType)
        {

            ArrayList list;

            if (DBUtil.isExistedMultiList(targetType))
            {
                list = DBUtil.getTargetListFromMultiTable(targetType);
            }
            else
            {
                list = DBUtil.getMTargetInfo(targetType);
            }

            int nRow = 0;
            foreach (ArrayList tmp in list)
            {
                if (Config.Mvi.Pno.Equals(tmp[0].ToString()) == true) continue;

                DataRow row = tbl.NewRow();

                row[0] = nRow + 1;
                row[1] = tmp[0];
                row[2] = tmp[1];
                row[3] = tmp[2];

                tbl.Rows.Add(row);

                //다면평가정보를 DataGridView에 설정
                setMultiInfoToGrid(nRow, tmp[0].ToString());

                nRow++;

            }

            
            lblDate.Text = "";

            if (cboTargetType.SelectedIndex > 0)
            {
                dgvMultiTable.EditMode = DataGridViewEditMode.EditOnEnter;
                dgvMultiTable.Columns[0].ReadOnly = true;
                dgvMultiTable.Columns[2].ReadOnly = true;
                dgvMultiTable.Columns[3].ReadOnly = true;
                dgvMultiTable.Columns[9].ReadOnly = true;
                dgvMultiTable.SelectionMode = DataGridViewSelectionMode.CellSelect;
            }
            else
            {
                dgvMultiTable.EditMode = DataGridViewEditMode.EditProgrammatically;
                dgvMultiTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }

            dgvMultiTable.Columns[1].Visible = false;
            dgvMultiTable.Columns[0].Width = 40;
            dgvMultiTable.Columns[2].Width = 60;
            dgvMultiTable.Columns[3].Width = 70;
            dgvMultiTable.Columns[4].Width = 70;
            dgvMultiTable.Columns[5].Width = 70;
            dgvMultiTable.Columns[6].Width = 70;
            dgvMultiTable.Columns[7].Width = 70;
            dgvMultiTable.Columns[8].Width = 70;
            dgvMultiTable.Columns[9].Width = 55;
            dgvMultiTable.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvMultiTable.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvMultiTable.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvMultiTable.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[8].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[9].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvMultiTable.Columns[4].DefaultCellStyle.Format = "#0.000";            
            dgvMultiTable.Columns[5].DefaultCellStyle.Format = "#0.000";
            dgvMultiTable.Columns[6].DefaultCellStyle.Format = "#0.000";
            dgvMultiTable.Columns[7].DefaultCellStyle.Format = "#0.000";
            dgvMultiTable.Columns[8].DefaultCellStyle.Format = "#0.000";
            dgvMultiTable.Columns[9].DefaultCellStyle.Format = "#0.000";

        }


        //닫기 버튼을 클릭
        private void btnClose_Click(object sender, EventArgs e)
        {
            clearElementsPoint();

            //DataGridView의 모든 행을 지운다.
            clearGrid();

            //확장 패널 안보이게 하기
            this.SetBounds(this.Location.X,this.Location.Y,pMain.Size.Width + 6,this.Height);

            //대상자등록 메뉴와 평가자 정보 메뉴 Enabled
            mnuMTargetsReg.Enabled = true;
            mnuValuerInfo.Enabled = true;

            //버튼 비활성
            btnUp.Enabled       = false;
            btnDown.Enabled     = false;
            btnAllot.Enabled    = false;
            btnSave.Enabled     = false;
            btnApply.Enabled    = false;
            btnOpen.Enabled = true;
        }

       
        private void mnuOpen_Click(object sender, EventArgs e)
        {
            btnOpen.PerformClick();
        }

        private void mnuClose_Click_1(object sender, EventArgs e)
        {
            btnClose.PerformClick();
        }


        //폼이 로드 될 때
        private void FormMain_Load(object sender, EventArgs e)
        {
            //확장 패널 안보이게 하기
            this.SetBounds(this.Location.X, this.Location.Y, pMain.Size.Width + 6, this.Height);

            if (Config.State == Config.STATE_INIT)
            {
                this.setDisabled();
                if (MessageBox.Show("프로그램을 처음으로 실행시키셨습니다.\n\n평가자정보를 입력해야지만 프로그램을 정상적으로 사용하실 수 있습니다.\n\n지금 평가자정보를 입력하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    mnuValuerInfo.PerformClick();
                }
            }

            if (Config.State == Config.STATE_OK)
            {
                //로그인 창 띄우기
                Form f = new FormLogin();

                if (f.ShowDialog() == DialogResult.Cancel)
                {
                    Config.State = Config.STATE_EXIT;
                    Application.Exit();
                    return;
                }
            }

            //버튼 비활성
            btnUp.Enabled       = false;
            btnDown.Enabled     = false;
            btnAllot.Enabled    = false;
            btnSave.Enabled     = false;
            btnApply.Enabled    = false;            

            addGridViewColumns();

            lblTargetNum.Text = DBUtil.countMTarget((byte)cboTargetType.SelectedIndex).ToString();
            lblMultiNum.Text = DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex).ToString();
            this.Text = this.Text + "( " +Config.Mvi.Name + " )";

            dgvMultiTable.Columns[3].Frozen = true;

            //대상자유형 초기화
            cboTargetType.SelectedIndex = 0;

        }       


        //위로 버튼 클릭
        private void btnUp_Click(object sender, EventArgs e)
        {

            try
            {

                DataGridViewSelectedRowCollection dgvRow = dgvMultiTable.SelectedRows;

                if (dgvRow.Count == 0)
                {
                    MessageBox.Show("목록에서 다면평가대상자를 먼저 선택하신 후 순위를 변경하십시오.   ", "확인");
                    return;
                }

                if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) == 0)
                {
                    MessageBox.Show("다면평가 대상자를 먼저 등록하세요!   ", "확인");
                    return;
                }

                foreach (DataGridViewRow row in dgvRow)
                {
                    if (row.Index == 0)
                    {
                        MessageBox.Show("최상위 행입니다.   ", "확인");
                        return;
                    }

                    string tmp_pcode;
                    string tmp_name;
                    string tmp_subject;


                    tmp_pcode = row.Cells[1].Value.ToString();
                    tmp_name = row.Cells[2].Value.ToString();
                    tmp_subject = row.Cells[3].Value.ToString();

                    row.Cells[1].Value = dgvMultiTable.Rows[row.Index - 1].Cells[1].Value;
                    row.Cells[2].Value = dgvMultiTable.Rows[row.Index - 1].Cells[2].Value;
                    row.Cells[3].Value = dgvMultiTable.Rows[row.Index - 1].Cells[3].Value;

                    dgvMultiTable.Rows[row.Index - 1].Cells[1].Value = tmp_pcode;
                    dgvMultiTable.Rows[row.Index - 1].Cells[2].Value = tmp_name;
                    dgvMultiTable.Rows[row.Index - 1].Cells[3].Value = tmp_subject;

                    dgvMultiTable.Rows[row.Index - 1].Selected = true;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace,"오류");
            }
            
        }

        //아래로 버튼을 클릭
        private void btnDown_Click(object sender, EventArgs e)
        {
            try
            {

                DataGridViewSelectedRowCollection dgvRow = dgvMultiTable.SelectedRows;

                if (dgvRow.Count == 0)
                {
                    MessageBox.Show("목록에서 다면평가대상자를 먼저 선택하신 후 순위를 변경하십시오.   ", "확인");
                    return;
                }

                if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) == 0)
                {
                    MessageBox.Show("다면평가 대상자를 먼저 등록하세요!   ", "확인");
                    return;
                }

                foreach (DataGridViewRow row in dgvRow)
                {
                    if (row.Index == DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) - 1)
                    {
                        MessageBox.Show("최하위 행입니다.   ", "확인");
                        return;
                    }

                    string tmp_pcode;
                    string tmp_name;
                    string tmp_subject;

                    tmp_pcode = row.Cells[1].Value.ToString();
                    tmp_name = row.Cells[2].Value.ToString();
                    tmp_subject = row.Cells[3].Value.ToString();

                    row.Cells[1].Value = dgvMultiTable.Rows[row.Index + 1].Cells[1].Value;
                    row.Cells[2].Value = dgvMultiTable.Rows[row.Index + 1].Cells[2].Value;
                    row.Cells[3].Value = dgvMultiTable.Rows[row.Index + 1].Cells[3].Value;

                    dgvMultiTable.Rows[row.Index + 1].Cells[1].Value = tmp_pcode;
                    dgvMultiTable.Rows[row.Index + 1].Cells[2].Value = tmp_name;
                    dgvMultiTable.Rows[row.Index + 1].Cells[3].Value = tmp_subject;

                    dgvMultiTable.Rows[row.Index + 1].Selected = true;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }


        private void mnuInitTagets_Click(object sender, EventArgs e)
        {
            if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) > 0)
            {
                if (MessageBox.Show("등록된 다면평가대상자 정보를 모두 지우시겠습니까?     ", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    
                    DBUtil.setInitTargetes(cboTargetType.SelectedIndex);

                    Config.NumOfTagets = DBUtil.getNumOfTagets(cboTargetType.SelectedIndex);
                    clearGrid();
                    lblTargetNum.Text = "0";

                    MessageBox.Show("모두 삭제하였습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    btnExtClose.PerformClick();
                }
            }
            else
            {
                MessageBox.Show("등록된 다면평가대상자가 없습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void mnuInitValueInfo_Click(object sender, EventArgs e)
        {
            if (DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex) > 0)
            {
                if (MessageBox.Show("다면평가정보를 모두 지우시겠습니까?     ", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {                    
                    DBUtil.setInitMultiInfo(cboTargetType.SelectedIndex);
                    clearGrid();
                    lblMultiNum.Text = "0";
                    MessageBox.Show("모두 삭제하였습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnExtClose.PerformClick();
                }
            }
            else
            {
                MessageBox.Show("다면평가정보가 없습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        private void btnAllot_Click(object sender, EventArgs e)
        {
            try
            {

                int numOfTargets = DBUtil.countMTarget((byte)cboTargetType.SelectedIndex);
                if (numOfTargets == 0)
                {
                    MessageBox.Show("다면평가 대상자를 먼저 등록하세요!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //인원 비율에 따라 수,우,미 인원 추출
                ArrayList rnum = DBUtil.getRatioNum(numOfTargets);

                Int16 su_num = (Int16)rnum[0];//수
                Int16 wo_num = (Int16)rnum[1];//우
                Int16 mi_num = (Int16)((Int16)rnum[2] + (Int16)rnum[3]);//미+양
                
                //평어 인원에 따라 순차적으로 총점 배점
                ArrayList totalSu = DBUtil.getTotalSu(Int32.Parse(rnum[0].ToString()));
                ArrayList totalWo = DBUtil.getTotalWo(Int32.Parse(rnum[1].ToString()));
                ArrayList totalMi = DBUtil.getTotalMi(Int32.Parse(rnum[2].ToString()) + Int32.Parse(rnum[3].ToString()));

                Random rnd = new Random();
                Random rnd1 = new Random();//부호랜덤
                int chk;

                for(int i = 0;i< totalSu.Count;i++)
                {
                    chk = rnd1.Next(100);

                    double tmp = Double.Parse(totalSu[i].ToString()) + (chk % 2 == 0 ? Util.getRandomRange(su_num) * rnd.NextDouble() : -1 * Util.getRandomRange(su_num) * rnd.NextDouble());
                    if (tmp > 100) tmp = 100.00;
                    if (tmp < 95) tmp = 95.00;

                    //요소별 랜덤 작성
                    double dRandom1 = rnd.NextDouble();
                    double item1 = tmp * 0.1;
                    int chkItem1 = rnd.Next(100);
                    item1 += (chkItem1 % 2 == 0 ? dRandom1 * 0.025 : (-1) * dRandom1 * 0.025);
                    if (item1 > 10.00) item1 = 10.00;

                    double dRandom2 = rnd.NextDouble();
                    double item2 = tmp * 0.1;
                    int chkItem2 = rnd.Next(100);
                    item2 += (chkItem2 % 2 == 0 ? dRandom2 * 0.025 : (-1) * dRandom2 * 0.025);
                    if (item2 > 10.00) item2 = 10.00;

                    double dRandom3 = rnd.NextDouble();
                    double item5 = tmp * 0.2;
                    int chkItem3 = rnd.Next(100);
                    item5 += (chkItem3 % 2 == 0 ? dRandom3 * 0.05 : (-1) * dRandom3 * 0.05);
                    if (item5 > 20.00) item5 = 20.00;

                    double dRandom4 = rnd.NextDouble();
                    double item4 = tmp * 0.2;
                    int chkItem4 = rnd.Next(100);
                    item4 += (chkItem4 % 2 == 0 ? dRandom4 * 0.05 : (-1) * dRandom4 * 0.05);
                    if (item4 > 20.00) item4 = 20.00;

                    double item3 = tmp - (item1 + item2 + item5 + item4);
                    if (item3 > 40.00)
                    {
                        tmp = tmp - (item3 - 40.00);
                        item3 = 40.00;
                    }

                    dgvMultiTable.Rows[i].Cells[4].Value = item1;
                    dgvMultiTable.Rows[i].Cells[5].Value = item2;
                    dgvMultiTable.Rows[i].Cells[6].Value = item3;
                    dgvMultiTable.Rows[i].Cells[7].Value = item4;
                    dgvMultiTable.Rows[i].Cells[8].Value = item5;
                    dgvMultiTable.Rows[i].Cells[9].Value = tmp;



                }                

                for (int i = totalSu.Count; i < (totalSu.Count + totalWo.Count); i++)
                {
                    chk = rnd1.Next(100);
                    double tmp = Double.Parse(totalWo[i - totalSu.Count].ToString()) + (chk % 2 == 0 ? Util.getRandomRange(wo_num) * rnd.NextDouble() : -1 * Util.getRandomRange(wo_num) * rnd.NextDouble());
                    if (tmp > 94.9) tmp = 94.9;
                    if (tmp < 90) tmp = 90.00;

                    //요소별 랜덤 작성
                    double dRandom1 = rnd.NextDouble();
                    double item1 = tmp * 0.1;
                    int chkItem1 = rnd.Next(100);
                    item1 += (chkItem1 % 2 == 0 ? dRandom1 * 0.025 : (-1) * dRandom1 * 0.025);
                    if (item1 > 10.00) item1 = 10.00;

                    double dRandom2 = rnd.NextDouble();
                    double item2 = tmp * 0.1;
                    int chkItem2 = rnd.Next(100);
                    item2 += (chkItem2 % 2 == 0 ? dRandom2 * 0.025 : (-1) * dRandom2 * 0.025);
                    if (item2 > 10.00) item2 = 10.00;

                    double dRandom3 = rnd.NextDouble();
                    double item5 = tmp * 0.2;
                    int chkItem3 = rnd.Next(100);
                    item5 += (chkItem3 % 2 == 0 ? dRandom3 * 0.05 : (-1) * dRandom3 * 0.05);
                    if (item5 > 20.00) item5 = 20.00;

                    double dRandom4 = rnd.NextDouble();
                    double item4 = tmp * 0.2;
                    int chkItem4 = rnd.Next(100);
                    item4 += (chkItem4 % 2 == 0 ? dRandom4 * 0.025 : (-1) * dRandom4 * 0.025);
                    if (item4 > 20.00) item4 = 20.00;

                    double item3 = tmp - (item1 + item2 + item5 + item4);

                    dgvMultiTable.Rows[i].Cells[4].Value = item1;
                    dgvMultiTable.Rows[i].Cells[5].Value = item2;
                    dgvMultiTable.Rows[i].Cells[6].Value = item3;
                    dgvMultiTable.Rows[i].Cells[7].Value = item4;
                    dgvMultiTable.Rows[i].Cells[8].Value = item5;
                    dgvMultiTable.Rows[i].Cells[9].Value = tmp;
                }

                

                for (int i = (totalSu.Count + totalWo.Count); i < (totalSu.Count + totalWo.Count + totalMi.Count); i++)
                {

                    chk = rnd1.Next(100);
                    double tmp = Double.Parse(totalMi[i - (totalSu.Count + totalWo.Count)].ToString()) + (chk % 2 == 0 ? Util.getRandomRange(wo_num) * rnd.NextDouble() : -1 * Util.getRandomRange(wo_num) * rnd.NextDouble());
                    if (tmp > 90) tmp = 89.9;
                    if (tmp < 85) tmp = 85.00;

                    //요소별 랜덤 작성
                    double dRandom1 = rnd.NextDouble();
                    double item1 = tmp * 0.1;
                    int chkItem1 = rnd.Next(100);
                    item1 += (chkItem1 % 2 == 0 ? dRandom1 * 0.025 : (-1) * dRandom1 * 0.025);
                    if (item1 > 10.00) item1 = 10.00;

                    double dRandom2 = rnd.NextDouble();
                    double item2 = tmp * 0.1;
                    int chkItem2 = rnd.Next(100);
                    item2 += (chkItem2 % 2 == 0 ? dRandom2 * 0.05 : (-1) * dRandom2 * 0.05);
                    if (item2 > 10.00) item2 = 10.00;

                    double dRandom3 = rnd.NextDouble();
                    double item5 = tmp * 0.2;
                    int chkItem3 = rnd.Next(100);
                    item5 += (chkItem3 % 2 == 0 ? dRandom3 * 0.025 : (-1) * dRandom3 * 0.025);
                    if (item5 > 20.00) item5 = 20.00;

                    double dRandom4 = rnd.NextDouble();
                    double item4 = tmp * 0.2;
                    int chkItem4 = rnd.Next(100);
                    item4 += (chkItem4 % 2 == 0 ? dRandom4 * 0.025 : (-1) * dRandom4 * 0.025);
                    if (item4 > 20.00) item4 = 20.00;

                    double item3 = tmp - (item1 + item2 + item5 + item4);

                    dgvMultiTable.Rows[i].Cells[4].Value = item1;
                    dgvMultiTable.Rows[i].Cells[5].Value = item2;
                    dgvMultiTable.Rows[i].Cells[6].Value = item3;
                    dgvMultiTable.Rows[i].Cells[7].Value = item4;
                    dgvMultiTable.Rows[i].Cells[8].Value = item5;
                    dgvMultiTable.Rows[i].Cells[9].Value = tmp;

                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            

            try
            {
                if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) == 0)
                {
                    MessageBox.Show("다면평가 대상자를 먼저 등록하세요!    ", "확인");
                    return;
                }

                if (dgvMultiTable.Rows[0].Cells[3].Value.ToString().Equals("") == true)
                {
                    MessageBox.Show("배점을 먼저 하신 후 저장하세요!    ", "확인");
                    return;
                }

                int maxNum = DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) - ((cboTargetType.SelectedIndex > 0) ? 0 : 1);

                for (int i = 0; i < maxNum; i++)
                {
                    ArrayList arr = new ArrayList();
                    arr.Add(dgvMultiTable.Rows[i].Cells[0].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[1].Value);
                    arr.Add(Config.Mvi.Pno);
                    arr.Add(dgvMultiTable.Rows[i].Cells[4].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[5].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[6].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[7].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[8].Value);
                    arr.Add(dgvMultiTable.Rows[i].Cells[9].Value);
                    DateTime now = DateTime.Now;
                    arr.Add(now);

                    if (DBUtil.isExistedMultiInfo(dgvMultiTable.Rows[i].Cells[1].Value) == true)
                    {
                        DBUtil.updateMultiInfo(arr);
                    }
                    else
                    {
                        DBUtil.insertMultiInfo(arr);
                    }

                }

                lblMultiNum.Text = DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex).ToString();                   

            }
            catch (Exception ex)
            {
                MessageBox.Show("[" + ex.Source + "]" + ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);

        
        }

        private NumericUpDown selectedItem(int i)
        {
            NumericUpDown result = null;

            if (rdoItem1.Checked == true && i != 1)
            {
                result = numItem1;
            }
            else if (rdoItem2.Checked == true && i != 2)
            {
                result = numItem2;
            }
            else if (rdoItem3.Checked == true && i != 3)
            {
                result = numItem3;
            }
            else if (rdoItem4.Checked == true && i != 4)
            {
                result = numItem4;
            }
            else if (rdoItem5.Checked == true && i != 5)
            {
                result = numItem5;
            }

            return result;
        }

        private void numItem1_ValueChanged(object sender, EventArgs e)
        {
            try
            {                

                if (Config.EnabledListViewEvent == true)
                {
                    double item1 = Double.Parse(numItem1.Value.ToString());
                    double item2 = Double.Parse(numItem2.Value.ToString());
                    double item3 = Double.Parse(numItem3.Value.ToString());
                    double item4 = Double.Parse(numItem4.Value.ToString());
                    double item5 = Double.Parse(numItem5.Value.ToString());
                    
                    double total = item1 + item2 + item3 + item4 + item5;
                    double originTotal = Double.Parse(txtTotal.Text);
                    double diff = originTotal - total;
                    double result = double.Parse(selectedItem(1).Value.ToString()) + diff;

                    Config.EnabledListViewEvent = false;
                    selectedItem(1).Value = Decimal.Parse(result.ToString());
                    Config.EnabledListViewEvent = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }


        private void numItem2_ValueChanged(object sender, EventArgs e)
        {
            try
            {

                if (Config.EnabledListViewEvent == true)
                {
                    double item1 = Double.Parse(numItem1.Value.ToString());
                    double item2 = Double.Parse(numItem2.Value.ToString());
                    double item3 = Double.Parse(numItem3.Value.ToString());
                    double item4 = Double.Parse(numItem4.Value.ToString());
                    double item5 = Double.Parse(numItem5.Value.ToString());

                    double total = item1 + item2 + item3 + item4 + item5;
                    double originTotal = Double.Parse(txtTotal.Text);
                    double diff = originTotal - total;
                    double result = double.Parse(selectedItem(2).Value.ToString()) + diff;

                    Config.EnabledListViewEvent = false;
                    selectedItem(2).Value = Decimal.Parse(result.ToString());
                    Config.EnabledListViewEvent = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }


        private void numItem3_ValueChanged(object sender, EventArgs e)
        {
            try
            {

                if (Config.EnabledListViewEvent == true)
                {
                    double item1 = Double.Parse(numItem1.Value.ToString());
                    double item2 = Double.Parse(numItem2.Value.ToString());
                    double item3 = Double.Parse(numItem3.Value.ToString());
                    double item4 = Double.Parse(numItem4.Value.ToString());
                    double item5 = Double.Parse(numItem5.Value.ToString());

                    double total = item1 + item2 + item3 + item4 + item5;
                    double originTotal = Double.Parse(txtTotal.Text);
                    double diff = originTotal - total;
                    double result = double.Parse(selectedItem(3).Value.ToString()) + diff;

                    Config.EnabledListViewEvent = false;
                    selectedItem(3).Value = Decimal.Parse(result.ToString());
                    Config.EnabledListViewEvent = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }

        private void numItem4_ValueChanged(object sender, EventArgs e)
        {
            try
            {

                if (Config.EnabledListViewEvent == true)
                {
                    double item1 = Double.Parse(numItem1.Value.ToString());
                    double item2 = Double.Parse(numItem2.Value.ToString());
                    double item3 = Double.Parse(numItem3.Value.ToString());
                    double item4 = Double.Parse(numItem4.Value.ToString());
                    double item5 = Double.Parse(numItem5.Value.ToString());

                    double total = item1 + item2 + item3 + item4 + item5;
                    double originTotal = Double.Parse(txtTotal.Text);
                    double diff = originTotal - total;
                    double result = double.Parse(selectedItem(4).Value.ToString()) + diff;

                    Config.EnabledListViewEvent = false;
                    selectedItem(4).Value = Decimal.Parse(result.ToString());
                    Config.EnabledListViewEvent = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }

        private void numItem5_ValueChanged(object sender, EventArgs e)
        {
            try
            {

                if (Config.EnabledListViewEvent == true)
                {
                    double item1 = Double.Parse(numItem1.Value.ToString());
                    double item2 = Double.Parse(numItem2.Value.ToString());
                    double item3 = Double.Parse(numItem3.Value.ToString());
                    double item4 = Double.Parse(numItem4.Value.ToString());
                    double item5 = Double.Parse(numItem5.Value.ToString());

                    double total = item1 + item2 + item3 + item4 + item5;
                    double originTotal = Double.Parse(txtTotal.Text);
                    double diff = originTotal - total;
                    double result = double.Parse(selectedItem(5).Value.ToString()) + diff;

                    Config.EnabledListViewEvent = false;
                    selectedItem(5).Value = Decimal.Parse(result.ToString());
                    Config.EnabledListViewEvent = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
            }
        }

        

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void mnuSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex) > 0)
                {
                    this.TopMost = false;

                    Thread t = new Thread(new ThreadStart(submitToXls));
                    t.Start();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류");
            }
            
        }

        private void dgvMultiTable_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {            

            if (e.RowIndex >= 0)
            {

                clearElementsPoint();

                lblTarget.Text = dgvMultiTable.Rows[e.RowIndex].Cells[2].Value.ToString();

                txtTotal.Text = Double.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[9].Value.ToString()).ToString("#0.000");

                numItem1.Value = Decimal.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[4].Value.ToString());
                numItem2.Value = Decimal.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[5].Value.ToString());
                numItem3.Value = Decimal.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[6].Value.ToString());
                numItem4.Value = Decimal.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[7].Value.ToString());
                numItem5.Value = Decimal.Parse(dgvMultiTable.Rows[e.RowIndex].Cells[8].Value.ToString());

                Config.EnabledListViewEvent = true;

                numItem1.Enabled = false;
                numItem2.Enabled = false;
                numItem3.Enabled = false;
                numItem4.Enabled = false;
                numItem5.Enabled = false;

                rdoItem1.Checked = false;
                rdoItem2.Checked = false;
                rdoItem3.Checked = false;
                rdoItem4.Checked = false;
                rdoItem5.Checked = false;

                checkCount = 0;

            }
        }
        
        private void btnApply_Click(object sender, EventArgs e)
        {
            DataGridViewCell currentCell = dgvMultiTable.CurrentCell;

            int rowIndex = currentCell.RowIndex;

            if (rowIndex >= 0 && rowIndex < dgvMultiTable.Rows.Count && numItem1.Value != 0)
            {

                dgvMultiTable.Rows[rowIndex].Cells[4].Value = numItem1.Value;
                dgvMultiTable.Rows[rowIndex].Cells[5].Value = numItem2.Value;
                dgvMultiTable.Rows[rowIndex].Cells[6].Value = numItem3.Value;
                dgvMultiTable.Rows[rowIndex].Cells[7].Value = numItem4.Value;
                dgvMultiTable.Rows[rowIndex].Cells[8].Value = numItem5.Value;


                DataGridViewSelectedRowCollection row = dgvMultiTable.SelectedRows;
                foreach (DataGridViewRow tmp in row)
                {
                    ArrayList arr = new ArrayList();
                    arr.Add(tmp.Cells[1].Value);
                    arr.Add(tmp.Cells[4].Value);
                    arr.Add(tmp.Cells[5].Value);
                    arr.Add(tmp.Cells[6].Value);
                    arr.Add(tmp.Cells[7].Value);
                    arr.Add(tmp.Cells[8].Value);

                    DBUtil.updateMultiItem(arr);
                }
                

                Config.EnabledListViewEvent = false;

                numItem1.Value = 0;
                numItem2.Value = 0;
                numItem3.Value = 0;
                numItem4.Value = 0;
                numItem5.Value = 0;

                txtTotal.Text = "";

                lblTarget.Text = "오른쪽 목록에서 대상자를 선택하세요.";

            }

        }



        private void FormMain_Shown(object sender, EventArgs e)
        {
            dgvMultiTable.CurrentCell = null;
        }



        /*********************************
         * 메서드 모음
         ********************************/

        private void setEnabled()
        {
            mnuOpen.Enabled             = true;
            mnuConfig.Enabled           = true;
            mnuSubmit.Enabled           = true;
            mnuMTargetsReg.Enabled      = true;
            btnOpen.Enabled             = true;
            btnClose.Enabled            = true;
            btnUp.Enabled               = true;
            btnDown.Enabled             = true;
            btnAllot.Enabled            = true;
            btnSave.Enabled             = true;
            btnApply.Enabled            = true;

        }

        public static void setStaticEnabled()
        {
            mnuStaticOpen.Enabled       = true;
            mnuStaticConfig.Enabled     = true;
            mnuStaticSubmit.Enabled     = true;
            mnuStaticMTagetsReg.Enabled = true;
            btnStaticOpen.Enabled       = true;
            btnStaticClose.Enabled      = true;
            btnStaticUp.Enabled         = true;
            btnStaticDown.Enabled       = true;
            btnStaticAllot.Enabled      = true;
            btnStaticSave.Enabled       = true;
            btnStaticApply.Enabled      = true;
            Config.setMvi();
        }

        private void setDisabled()
        {
            mnuOpen.Enabled             = false;
            mnuConfig.Enabled           = false;
            mnuSubmit.Enabled           = false;
            mnuMTargetsReg.Enabled      = false;
            btnOpen.Enabled             = false;
            btnClose.Enabled            = false;
            btnUp.Enabled               = false;
            btnDown.Enabled             = false;
            btnAllot.Enabled            = false;
            btnSave.Enabled             = false;
            btnApply.Enabled            = false;
        }

        private void setStaticControls()
        {
            FormMain.mnuStaticOpen          = mnuOpen;
            FormMain.mnuStaticConfig        = mnuConfig;
            FormMain.mnuStaticSubmit        = mnuSubmit;
            FormMain.mnuStaticMTagetsReg    = mnuMTargetsReg;
            FormMain.btnStaticOpen          = btnOpen;
            FormMain.btnStaticClose         = btnClose;
            FormMain.btnStaticUp            = btnUp;
            FormMain.btnStaticDown          = btnDown;
            FormMain.btnStaticAllot         = btnAllot;
            FormMain.btnStaticSave          = btnSave;
            FormMain.btnStaticApply         = btnApply;
        }


        private void mnuMTargetsReg_Click(object sender, EventArgs e)
        {
            if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) > 0)
            {
                MessageBox.Show("다면평가대상자들이 이미 등록되어 있습니다.\n\n새로 등록하시려면 초기화 후 다시 시도하십시오.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                Form f = new FormMTargetAdd(this, lblTargetNum, cboTargetType.SelectedIndex);
                f.ShowDialog(this);
            }
        }


        private double calculateTotalPoint()
        {
            double item1 = (double)numItem1.Value;
            double item2 = (double)numItem2.Value;
            double item3 = (double)numItem3.Value;
            double item4 = (double)numItem4.Value;
            double item5 = (double)numItem5.Value;

            return item1 + item2 + item3 + item4 + item5;
        }

        

        private void addGridViewColumns()
        {
            DataColumn col;            

            //순위
            col = new DataColumn();
            col.DataType = Type.GetType("System.Int32");
            col.ColumnName = "순위";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //개인번호
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "개인번호";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평가자 대상자 성명
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "성명";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //과목
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "과목";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육자로서의 품성
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "교육자로서의 품성(10)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //공직자로서의 자세
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "공직자로서의 자세(10)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //학습지도
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "학습지도(40)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //생활지도
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "생활지도(20)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육연구 및 담당업무
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "교육연구 및 담당업무(20)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);


            //총점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "총점(100)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);


            dgvMultiTable.DataSource = tbl;


        }

        private void clearGrid()
        {
            int rowCount = dgvMultiTable.Rows.Count;
            if (rowCount == 0) return;

            for (int i = rowCount - 1; i >= 0; i--)
            {
                dgvMultiTable.Rows.RemoveAt(i);                
            }
            
        }

       

        private void clearElementsPoint()
        {
            Config.EnabledListViewEvent = false;

            numItem1.Value = new Decimal(0);
            numItem2.Value = new Decimal(0);
            numItem3.Value = new Decimal(0);
            numItem4.Value = new Decimal(0);
            numItem5.Value = new Decimal(0);
            txtTotal.Text = "";
            lblTarget.Text = "오른쪽 목록에서 대상자를 선택하세요.";
        }

        private void numItem1_Click(object sender, EventArgs e)
        {
            originItemValue = numItem1.Value;
            numItem1.Select(0, 5);
        }

        private void numItem2_Click(object sender, EventArgs e)
        {
            originItemValue = numItem2.Value;
            numItem2.Select(0, 5);
        }

        private void numItem3_Click(object sender, EventArgs e)
        {
            originItemValue = numItem3.Value;
            numItem3.Select(0, 5);
        }

        private void numItem4_Click(object sender, EventArgs e)
        {
            originItemValue = numItem4.Value;
            numItem4.Select(0, 5);
        }

        private void numItem5_Click(object sender, EventArgs e)
        {
            originItemValue = numItem5.Value;
            numItem5.Select(0, 5);
        }



        private void submitToXls()
        {
            FileInfo f;

            try
            {

                Util.openXls(Application.StartupPath + "\\MultiEvalue.xls");

                Excel.Range range = Util.OSheet.get_Range("B2", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Pno);

                range = Util.OSheet.get_Range("H2", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Name);

                object[,] arr = new object[DBUtil.countMTarget((byte)cboTargetType.SelectedIndex), 9];

                //지정된 사용자 유형의 다면평가대상자들의정보불러오기
                ArrayList list = DBUtil.getMultipleInformations((byte)cboTargetType.SelectedIndex);

                int i = 0;
                foreach (ArrayList tmp in list)
                {
                    if (Config.Mvi.Pno.Equals(tmp[0].ToString()) == false)//평가자 본인 제외
                    {
                        arr[i, 0] = i + 1;
                        arr[i, 1] = tmp[0];
                        string name = DBUtil.getTargetName(tmp[0].ToString());
                        if (DBUtil.getSameNameExist(name)) name = name + "(" + DBUtil.getMTargetInfo(tmp[0].ToString())[2].ToString() + ")";
                        arr[i, 2] = name;
                        arr[i, 3] = tmp[1];
                        arr[i, 4] = tmp[2];
                        arr[i, 5] = tmp[3];
                        arr[i, 6] = tmp[4];
                        arr[i, 7] = tmp[5];
                        arr[i, 8] = tmp[6];

                        i++;
                    }

                }

                int titleRow = cboTargetType.SelectedIndex == 0?4:5;
                
                range = Util.OSheet.get_Range("A6", "I" + (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) + titleRow).ToString());
                range.set_Value(Missing.Value, arr);

                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;

                string myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string fileName = myDocPath + "\\" + Config.Mvi.Pno + "(" + Config.Mvi.Name + ")_" + (string)cboTargetType.Items[cboTargetType.SelectedIndex] + ".xls";
                f = new FileInfo(fileName);
                if (f.Exists)
                {
                    f.Delete();
                }

                Util.OWorkBook.SaveAs(fileName, Missing.Value, Config.xls_password, Config.xls_password, true, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Util.closeXls();

                this.TopMost = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show(f.Name + " 을 [내문서]에 내보냈습니다.    \n\n교감 선생님께 제출하세요!  ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
            f = null;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            int rowCount = DBUtil.countMTarget((byte)cboTargetType.SelectedIndex);

            if (DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex) > 0)
            {
                try
                {
                    Util.openXls(Application.StartupPath + "\\MultiEvalue.xls");

                    Excel.Range range = Util.OSheet.get_Range("B2", Missing.Value);
                    range.set_Value(Missing.Value, Config.Mvi.Pno);

                    range = Util.OSheet.get_Range("H2", Missing.Value);
                    range.set_Value(Missing.Value, Config.Mvi.Name);

                    object[,] arr = new object[rowCount, 9];
                    ArrayList list = DBUtil.getMultipleInformations((byte)cboTargetType.SelectedIndex);

                    int i = 0;
                    foreach (ArrayList tmp in list)
                    {
                        arr[i, 0] = i + 1;
                        arr[i, 1] = tmp[0];
                        string name = DBUtil.getTargetName(tmp[0].ToString());
                        if (DBUtil.getSameNameExist(name)) name = name + "(" + DBUtil.getMTargetInfo(tmp[0].ToString())[2].ToString() + ")";
                        arr[i, 2] = name;
                        arr[i, 3] = tmp[1];
                        arr[i, 4] = tmp[2];
                        arr[i, 5] = tmp[3];
                        arr[i, 6] = tmp[4];
                        arr[i, 7] = tmp[5];
                        arr[i, 8] = tmp[6];

                        i++;

                    }

                    int titleRow = cboTargetType.SelectedIndex == 0 ? 4 : 5;
                    range = Util.OSheet.get_Range("A6", "I" + (rowCount + titleRow).ToString());
                    range.set_Value(Missing.Value, arr);

                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;

                    
                    //int startPage = dlg.PrinterSettings.FromPage;
                    //int endPage = dlg.PrinterSettings.ToPage;
                    //Util.OSheet.PageSetup.CenterHorizontally = true;

                    //range = Util.OSheet.get_Range("A1", "I" + (rowCount + 4).ToString());                        
                    //if (startPage > 0 && endPage > 0)
                    //{
                    //    range.PrintOut(startPage, endPage, dlg.PrinterSettings.Copies, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    //}
                    //else
                    //{
                    //    range.PrintOut(Missing.Value, Missing.Value, dlg.PrinterSettings.Copies, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    //}
                    string myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string fileName = myDocPath + "\\" + Config.Mvi.Pno + "(" + Config.Mvi.Name + ")_" + (string)cboTargetType.Items[cboTargetType.SelectedIndex] + ".xls";
                    FileInfo f = new FileInfo(fileName);
                    if (f.Exists)
                    {
                        f.Delete();
                    }

                    Util.OWorkBook.SaveAs(fileName, Missing.Value, Config.xls_password, Missing.Value, true, Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    Util.OExcel.Visible = true;
                    Util.OWorkBook.PrintPreview(Missing.Value);

                    f.Delete();
                                     
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    Util.closeXls();
                }

                //MessageBox.Show("다면평가자별 평가표를 인쇄하였습니다.  ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }        

        private void btnMTargetReg_Click(object sender, EventArgs e)
        {
            if (DBUtil.countMTarget((byte)cboTargetType.SelectedIndex) > 0)
            {
                MessageBox.Show("다면평가대상자들이 이미 등록되어 있습니다.\n\n새로 등록하시려면 초기화 후 다시 시도하십시오.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                btnExtClose.PerformClick();

                FormMTargetAdd f = new FormMTargetAdd(this, lblTargetNum, cboTargetType.SelectedIndex);
                f.ShowDialog(this);
            }
        }

        private void cboTargetType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //대상자 유형에 따른 대상자수 및 다면평가한 수 갱신
            lblTargetNum.Text = DBUtil.countMTarget((byte)cboTargetType.SelectedIndex).ToString();
            lblMultiNum.Text = DBUtil.countMultiInfo((byte)cboTargetType.SelectedIndex).ToString();

            //닫기 버튼 클릭 수행
            btnExtClose.PerformClick();

            //열기 버튼 클릭 수행
            btnOpen.PerformClick();

            if (cboTargetType.SelectedIndex > 0)
            {
                btnAllot.Enabled = false;
                btnUp.Enabled = false;
                btnDown.Enabled = false;
            }
            else
            {
                btnAllot.Enabled = true;
                btnUp.Enabled = true;
                btnDown.Enabled = true;
            }
        }

        private void dgvMultiTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (cboTargetType.SelectedIndex == 0) return;

            int rowNum = e.RowIndex;
            int colNum = e.ColumnIndex;            

            double[] maxValue = new double[] { 10.0, 10.0, 40.0, 20.0, 20.0, 100.0 };

            double currValue = (double)dgvMultiTable.Rows[rowNum].Cells[colNum].Value;            

            if (currValue > maxValue[colNum - 4])
            {
                MessageBox.Show("해당 항목의 최대값은 " + maxValue[colNum - 4] + "점 입니다.  ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                dgvMultiTable.Rows[rowNum].Cells[colNum].Value = 0.0;
                return;
            }            

            calcMultiPoint(rowNum);

        }

        /// <summary>
        /// 대상자 유형이 일반이 아닌 경우 직접 합산을 한다
        /// </summary>
        /// <param name="rowNum">행번호</param>
        private void calcMultiPoint(int rowNum)
        {
            double[] point = new double[6] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
            point[0] = (double)dgvMultiTable.Rows[rowNum].Cells[4].Value;
            point[1] = (double)dgvMultiTable.Rows[rowNum].Cells[5].Value;
            point[2] = (double)dgvMultiTable.Rows[rowNum].Cells[6].Value;
            point[3] = (double)dgvMultiTable.Rows[rowNum].Cells[7].Value;
            point[4] = (double)dgvMultiTable.Rows[rowNum].Cells[8].Value;

            point[5] = point[0] + point[1] + point[2] + point[3] + point[4];

            dgvMultiTable.Rows[rowNum].Cells[9].Value = point[5];

        }

        
        private void rdoStateChange(int i)
        {
            if (i == 1)
            {
                rdoStateRecover();
                rdoItem1.Checked = false;
                rdoItem1.Enabled = false;
                numItem1.Enabled = true;
            }
            else if (i == 2)
            {
                rdoStateRecover();
                rdoItem2.Checked = false;
                rdoItem2.Enabled = false;
                numItem2.Enabled = true;
            }
            else if (i == 3)
            {
                rdoStateRecover();
                rdoItem3.Checked = false;
                rdoItem3.Enabled = false;
                numItem3.Enabled = true;
            }
            else if (i == 4)
            {
                rdoStateRecover();
                rdoItem4.Checked = false;
                rdoItem4.Enabled = false;
                numItem4.Enabled = true;
            }
            else if (i == 5)
            {
                rdoStateRecover();
                rdoItem5.Checked = false;
                rdoItem5.Enabled = false;
                numItem5.Enabled = true;
            }
        }

        private void rdoStateRecover()
        {
            rdoItem1.Checked = false;
            rdoItem1.Enabled = true;

            numItem1.Enabled = false;

            rdoItem2.Checked = false;
            rdoItem2.Enabled = true;

            numItem2.Enabled = false;

            rdoItem3.Checked = false;
            rdoItem3.Enabled = true;

            numItem3.Enabled = false;

            rdoItem4.Checked = false;
            rdoItem4.Enabled = true;

            numItem4.Enabled = false;

            rdoItem5.Checked = false;
            rdoItem5.Enabled = true;

            numItem5.Enabled = false;
        }

        private void rdoItem1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCount > 2 && rdoItem1.Checked == true)
            {
                rdoItem1.Checked = false;
                numItem1.Enabled = rdoItem1.Checked;
                checkCount--;
                return;
            }
            else if (checkCount > 2 && rdoItem1.Checked == false)
            {
                rdoItem1.Checked = false;
                numItem1.Enabled = rdoItem1.Checked;
                return;
            }

            numItem1.Enabled = rdoItem1.Checked;
            originItemValue = numItem1.Value;
            checkCount++;

        }

        private void rdoItem2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCount > 2 && rdoItem2.Checked == true)
            {
                rdoItem2.Checked = false;
                numItem2.Enabled = rdoItem1.Checked;
                checkCount--;
                return;
            }
            else if (checkCount > 2 && rdoItem2.Checked == false)
            {
                rdoItem2.Checked = false;
                numItem2.Enabled = rdoItem2.Checked;
                return;
            }

            numItem2.Enabled = rdoItem2.Checked;
            originItemValue = numItem2.Value;
            checkCount++;
        }

        private void rdoItem3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCount > 2 && rdoItem3.Checked == true)
            {
                rdoItem3.Checked = false;
                numItem3.Enabled = rdoItem1.Checked;
                checkCount--;
                return;
            }
            else if (checkCount > 2 && rdoItem3.Checked == false)
            {
                rdoItem3.Checked = false;
                numItem3.Enabled = rdoItem3.Checked;
                return;
            }

            numItem3.Enabled = rdoItem3.Checked;
            originItemValue = numItem3.Value;
            checkCount++;
        }

        private void rdoItem4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCount > 2 && rdoItem4.Checked == true)
            {
                rdoItem4.Checked = false;
                numItem4.Enabled = rdoItem4.Checked;
                checkCount--;
                return;
            }
            else if (checkCount > 2 && rdoItem4.Checked == false)
            {
                rdoItem4.Checked = false;
                numItem4.Enabled = rdoItem4.Checked;
                return;
            }

            numItem4.Enabled = rdoItem4.Checked;
            originItemValue = numItem4.Value;
            checkCount++;
        }

        private void rdoItem5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCount > 2 && rdoItem5.Checked == true)
            {
                rdoItem5.Checked = false;
                numItem5.Enabled = rdoItem5.Checked;
                checkCount--;
                return;
            }
            else if (checkCount > 2 && rdoItem5.Checked == false)
            {
                rdoItem5.Checked = false;
                numItem5.Enabled = rdoItem5.Checked;
                return;
            }

            numItem5.Enabled = rdoItem5.Checked;
            originItemValue = numItem5.Value;
            checkCount++;
        }

      
    }
}
